<template>
  <div class="checks-management">
    <h1>Medical Checks Management</h1>
    <el-card class="box-card">
      <div class="card-header">
        <el-button type="primary" @click="dialogVisible = true">Add New Medical Check</el-button>
        <el-input
          v-model="searchQuery"
          placeholder="Search medical checks..."
          style="width: 300px; margin-left: 16px;"
          clearable
        />
      </div>
      
      <el-table :data="filteredChecks" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="Name" width="150" />
        <el-table-column prop="type" label="Type" width="120" />
        <el-table-column prop="price" label="Price" width="120">
          <template #default="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="Duration (min)" width="120" />
        <el-table-column prop="department" label="Department" width="150" />
        <el-table-column prop="description" label="Description" />
        <el-table-column label="Operations" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">Edit</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row.id)"
            >
              Delete
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredChecks.length"
        class="pagination"
      />
    </el-card>

    <!-- Add/Edit Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? 'Edit Medical Check' : 'Add New Medical Check'"
      width="50%"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="Name" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="Type" prop="type">
          <el-select v-model="form.type" placeholder="Select type">
            <el-option value="Blood Test" label="Blood Test" />
            <el-option value="Imaging" label="Imaging" />
            <el-option value="Physical" label="Physical" />
            <el-option value="Specialized" label="Specialized" />
          </el-select>
        </el-form-item>
        <el-form-item label="Price" prop="price">
          <el-input-number v-model="form.price" :precision="2" :step="0.01" :min="0" />
        </el-form-item>
        <el-form-item label="Duration (min)" prop="duration">
          <el-input-number v-model="form.duration" :min="0" :step="5" />
        </el-form-item>
        <el-form-item label="Department" prop="department">
          <el-input v-model="form.department" />
        </el-form-item>
        <el-form-item label="Description" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="submitForm">Save</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCheckStore } from '../../stores/checks'

const checkStore = useCheckStore()

const checks = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const form = ref({
  id: null,
  name: '',
  type: '',
  price: 0,
  duration: 30,
  department: '',
  description: ''
})

const rules = {
  name: [{ required: true, message: 'Please enter check name', trigger: 'blur' }],
  type: [{ required: true, message: 'Please select check type', trigger: 'change' }],
  price: [{ required: true, message: 'Please enter price', trigger: 'blur' }],
  duration: [{ required: true, message: 'Please enter duration', trigger: 'blur' }],
  department: [{ required: true, message: 'Please enter department', trigger: 'blur' }]
}

const filteredChecks = computed(() => {
  const query = searchQuery.value.toLowerCase().trim()
  if (!query) return checks.value
  
  return checks.value.filter(check => 
    check.name.toLowerCase().includes(query) ||
    check.type.toLowerCase().includes(query) ||
    check.department.toLowerCase().includes(query) ||
    check.description.toLowerCase().includes(query)
  )
})

onMounted(async () => {
  await fetchChecks()
})

async function fetchChecks() {
  try {
    const response = await checkStore.getChecks()
    checks.value = response
  } catch (error) {
    ElMessage.error('Failed to load medical checks')
  }
}

function handleEdit(row) {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

async function handleDelete(id) {
  try {
    await ElMessageBox.confirm('Are you sure you want to delete this medical check?', 'Warning', {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning'
    })
    
    await checkStore.deleteCheck(id)
    ElMessage.success('Medical check deleted successfully')
    await fetchChecks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to delete medical check')
    }
  }
}

async function submitForm() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await checkStore.updateCheck(form.value)
          ElMessage.success('Medical check updated successfully')
        } else {
          await checkStore.createCheck(form.value)
          ElMessage.success('Medical check added successfully')
        }
        
        dialogVisible.value = false
        await fetchChecks()
        resetForm()
      } catch (error) {
        ElMessage.error(isEdit.value ? 'Failed to update medical check' : 'Failed to add medical check')
      }
    }
  })
}

function resetForm() {
  form.value = {
    id: null,
    name: '',
    type: '',
    price: 0,
    duration: 30,
    department: '',
    description: ''
  }
  isEdit.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
}
</script>

<style scoped>
.checks-management {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 